/* eslint-disable react/jsx-no-duplicate-props */
/* eslint-disable no-plusplus */
/* eslint-disable no-nested-ternary */
/* eslint-disable react/prop-types */
/* eslint-disable react/jsx-props-no-spreading */
import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import TreeView from '@mui/lab/TreeView';
import TreeItem, { treeItemClasses } from '@mui/lab/TreeItem';
import Typography from '@mui/material/Typography';
import * as Ant4Icons from '@ant-design/icons';

const {
  CaretRightFilled,
  CaretDownFilled,
  FolderFilled,
  FileFilled,
  TableOutlined,
} = Ant4Icons;

function strToHump(str) {
  const strArr = str.split('-');
  for (let i = 0; i < strArr.length; i++) {
    strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].substr(1);
  }
  const res = strArr.join('');
  return `${res}Outlined`;
}

const StyledTreeItemRoot = styled(TreeItem)(({ theme }) => ({
  color: theme.palette.text.secondary,
  [`& .${treeItemClasses.content}`]: {
    color: theme.palette.text.secondary,
    borderTopRightRadius: theme.spacing(2),
    borderBottomRightRadius: theme.spacing(2),
    paddingRight: theme.spacing(1),
    fontWeight: theme.typography.fontWeightMedium,
    '&.Mui-expanded': {
      fontWeight: theme.typography.fontWeightRegular,
    },
    '&:hover': {
      backgroundColor: theme.palette.action.hover,
    },
    '&.Mui-focused, &.Mui-selected, &.Mui-selected.Mui-focused': {
      backgroundColor: `var(--tree-view-bg-color, ${theme.palette.action.selected})`,
      color: 'var(--tree-view-color)',
    },
    [`& .${treeItemClasses.label}`]: {
      fontWeight: 'inherit',
      color: 'inherit',
    },
  },
  [`& .${treeItemClasses.group}`]: {
    marginLeft: 0,
    [`& .${treeItemClasses.content}`]: {
      paddingLeft: theme.spacing(2),
    },
  },
}));

function StyledTreeItem(props) {
  const {
    bgColor,
    color,
    labelIcon: LabelIcon,
    labelInfo,
    labelText,
    ...other
  } = props;

  return (
    <StyledTreeItemRoot
      label={
        <Box sx={{ display: 'flex', alignItems: 'center', p: 0.5, pr: 0 }}>
          <Box component={LabelIcon} color="inherit" sx={{ mr: 1 }} />
          <Typography
            variant="body2"
            sx={{ fontWeight: 'inherit', flexGrow: 1 }}
          >
            {labelText}
          </Typography>
          <Typography variant="caption" color="inherit">
            {labelInfo}
          </Typography>
        </Box>
      }
      style={{
        '--tree-view-color': color,
        '--tree-view-bg-color': bgColor,
      }}
      {...other}
    />
  );
}

const loop = (data, format, diybtn, onSelect) =>
  data &&
  data?.length > 0 &&
  data?.map?.((item) => {
    const { title, key, children } = format ?? {};
    const aname = title || 'name';
    const akey = key || 'path';
    const achild = children || 'children';

    const titles = <span>{item[aname]}</span>;
    if (item[achild]) {
      const icon = item.icon ? strToHump(item.icon) : null;
      const ItemIcon = Ant4Icons[icon];

      return (
        <StyledTreeItem
          onClick={() => {
            onSelect(item);
          }}
          nodeId={item[akey]}
          labelText={titles}
          labelIcon={ItemIcon || FolderFilled}
          labelInfo={
            diybtn
              ? [
                  diybtn?.edit?.(item),
                  diybtn?.add?.(item),
                  item[achild].length === 0 && diybtn?.delete(item),
                ]
              : item.size
              ? (item.size / 1024).toFixed(1) > 1024
                ? `${(item.size / 1024 / 1024).toFixed(1)}M`
                : `${(item.size / 1024).toFixed(1)}K`
              : null
          }
          key={item[akey]}
        >
          {loop(item[achild], format, diybtn, onSelect)}
        </StyledTreeItem>
      );
    }
    const icon = item.icon ? strToHump(item.icon) : null;
    const ItemIcon = Ant4Icons[icon];
    return (
      item[akey] && (
        <StyledTreeItem
          key={item[akey]}
          onClick={() => {
            onSelect(item);
          }}
          nodeId={item[akey]}
          labelText={titles}
          labelIcon={ItemIcon ?? FileFilled}
          labelInfo={
            diybtn
              ? [diybtn?.edit(item), diybtn?.delete(item)]
              : item.size
              ? (item.size / 1024).toFixed(1) > 1024
                ? `${(item.size / 1024 / 1024).toFixed(1)}M`
                : `${(item.size / 1024).toFixed(1)}K`
              : null
          }
        />
      )
    );
  });

export default function Tree({ data, onSelect, format, diybtn, curpage = {} }) {
  return (
    <TreeView
      aria-label="gmail"
      selected={[curpage.path]}
      defaultCollapseIcon={<CaretDownFilled />}
      defaultExpandIcon={<CaretRightFilled />}
      defaultEndIcon={<div style={{ width: 24 }} />}
      sx={{
        minHeight: 264,
        flexGrow: 1,
        maxWidth: 400,
        overflowY: 'auto',
        overflowX: 'hidden',
      }}
    >
      {loop(data, format, diybtn, onSelect)}
    </TreeView>
  );
}
